package com.imooc.newretail.bpl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.imooc.newretail.common.exceptions.BplException;
import com.imooc.newretail.bpl.entity.Dept;
import com.imooc.newretail.bpl.entity.TenantUser;
import com.imooc.newretail.bpl.enums.ErrCodeEnum;
import com.imooc.newretail.bpl.mapper.DeptMapper;
import com.imooc.newretail.bpl.service.IDeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imooc.newretail.bpl.service.ITenantUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 部门信息 服务实现类
 * </p>
 *
 * @author Hank
 * @since 2020-06-27
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {

    @Autowired
    ITenantUserService tenantUserService;

    @Override
    @Transactional
    public boolean removeDeptAndUser(String deptId) throws BplException {
        QueryWrapper query = new QueryWrapper();
        query.eq("dept_id", deptId);
        tenantUserService.remove(query);
        baseMapper.deleteById(deptId);
        return true;
    }

    /***
     * 添加用户到指定的租户部门
     * @param user
     * @return
     */
    @Override
    public boolean addUser(TenantUser user) throws BplException {
        if (StringUtils.isEmpty(user.getTenantId())
                || StringUtils.isEmpty(user.getDeptId())
                || StringUtils.isEmpty(user.getUserId())) {
            throw new BplException(ErrCodeEnum.PARAM_IS_EMPTY);
        }
        return tenantUserService.save(user);
    }

    /***
     * 根据部门ID获取用户列表
     * @param deptId
     * @return
     */
    @Override
    public List<TenantUser> getUsersByDeptId(String deptId) {
        QueryWrapper query = new QueryWrapper();
        query.eq("dept_id", deptId);
        return tenantUserService.list(query);
    }

    public boolean removeUser(String deptId, String userId) {
        QueryWrapper query = new QueryWrapper();
        query.eq("dept_id", deptId);
        query.eq("user_id", userId);
        return tenantUserService.remove(query);
    }


}
